package syncTest;

/**
 *
 * 脏读
 */
public class DirtyRead {


    private String name = "test" ;
    private String password =  "123456";


    public synchronized void setValue(String name, String password) {
        this.name = name;
        try {
            Thread.sleep(2000);
            this.password = password;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("set ... name=" + this.name +", password="+this.password);
    }

    /**
     *
     *  因为get不是同步方法，所以在调用set的时候，可以直接调用get
     *
     *  避免脏读，可以使用synchronized关键字，等待set完在get
     *
     */
    public synchronized void getValue(){
        System.out.println("get ... name=" + this.name +", password="+this.password);
    }


    public static void main(String[] args) {
        DirtyRead dr = new DirtyRead();

        Thread t1 = new Thread(() -> dr.setValue("weixin","11111"));
        t1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        dr.getValue();
    }


}
